package com.nexus.all.utils.wxUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nexus.bean.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WechatUtil {

    public static JSONObject getOpenid(RestTemplate httpTemplate, String appId, String secret, String url, String code) {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", secret);
        params.put("code", code);
        params.put("type", "authorization_code");
        log.info("获取用户openid url={},入参={}", url, JSON.toJSONString(params));
        String result = httpTemplate.getForObject(url, String.class, params);
        log.info("获取用户openid出参={}", result);
        if (StringUtils.isBlank(result)) {
            // 调用微信异常
            return null;
        }
        return JSONObject.parseObject(result);
    }

    public static JSONObject getAccessToken(RestTemplate httpTemplate, String appId, String secret, String url) {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", secret);
        log.info("获取公众号accesstoken url={},入参={}", url, JSON.toJSONString(params));
        String result = httpTemplate.getForObject(url, String.class, params);
        log.info("获取公众号accesstoken出参={}", result);
        if (StringUtils.isBlank(result)) {
            // 调用微信异常
            return null;
        }
        return JSONObject.parseObject(result);
    }

    public static JSONObject getTicket(RestTemplate httpTemplate, String accessToken, String url) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", accessToken);
        log.info("获取公众号jsapi_ticket url={},入参={}", url, JSON.toJSONString(params));
        String result = httpTemplate.getForObject(url, String.class, params);
        log.info("获取公众号jsapi_ticket出参={}", result);
        if (StringUtils.isBlank(result)) {
            // 调用微信异常
            return null;
        }
        return JSONObject.parseObject(result);
    }

    public static JSONObject getUserInfo(RestTemplate httpTemplate, String accessToken, String openid, String url) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", accessToken);
        params.put("openid", openid);
        log.info("获取用户信息 url={},入参={}", url, JSON.toJSONString(params));
        String result = httpTemplate.getForObject(url, String.class, params);
        log.info("获取用户信息jsapi_ticket出参={}", result);
        if (StringUtils.isBlank(result)) {
            // 调用微信异常
            return null;
        }
        return JSONObject.parseObject(result);
    }

    public static JSONObject sendTemplate(RestTemplate httpTemplate, String jsonStr, String url) {

        log.info("推送模版信息 url={},入参={}", url, JSON.toJSONString(jsonStr));
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("text/xml;charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonStr, headers);
        log.info("推送模版消息：携带编码请求头{}", requestEntity);
        String result = httpTemplate.postForObject(url, requestEntity, String.class);
        log.info("推送模版信息 出参={}", result);
        if (StringUtils.isBlank(result)) {
            // 调用微信异常
            return null;
        }
        return JSONObject.parseObject(result);
    }

    public static JSONObject qrCodeCreate(RestTemplate httpTemplate, String jsonStr, String url) {
        //Map<String, Object> params = new HashMap<>();
        //params.put("expire_seconds", nerateQrCodeDTO.getExpireSeconds());
        //params.put("action_name", nerateQrCodeDTO.getActionName());
        //Map<String, Object> map1 = new HashMap<>();
        //Map<String, Object> map2 = new HashMap<>();
        //map2.put("scene_id", nerateQrCodeDTO.getActionInfo().getScene().getSceneStr());
        //map1.put("scene", map2);
        //params.put("action_info", map1);
        log.info("生成带参数二维码 url={},入参={}", url, jsonStr);
        String result = httpTemplate.postForObject(url, jsonStr, String.class);
        log.info("生成带参数二维码 出参={}", result);
        if (StringUtils.isBlank(result)) {
            // 调用微信异常
            return null;
        }
        return JSONObject.parseObject(result);
    }


    /**
     * 加密
     *
     * @param str
     * @return
     */
    public static String sha1Encry(String str) {
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(str.getBytes(StandardCharsets.UTF_8));
            return byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static String gen(String... arr) {
        if (org.apache.commons.lang3.StringUtils.isAnyEmpty(arr)) {
            throw new IllegalArgumentException("非法请求参数，有部分参数为空 : " + Arrays.toString(arr));
        }
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        for (String a : arr) {
            sb.append(a);
        }
        return DigestUtils.sha1Hex(sb.toString());
    }


}
